local yuanfa = fk.CreateSkill{
  name = "hanqing__yuanfa",
}

Fk:loadTranslationTable{
  ["hanqing__yuanfa"] = "远伐",
  [":hanqing__yuanfa"] = "其他角色出牌阶段结束时，你可以与其拼点且你此次拼点牌点数-X：若你赢，视为对其使用一张额外亮出X张牌的【兵临城下】"..
  "（X为你计算与其距离）；若其赢，〖远伐〗失效直到你下回合开始。",

  ["#hanqing__yuanfa-invoke"] = "远伐：是否与 %dest 拼点（点数-%arg）？若赢，视为对其使用【兵临城下】",
}

yuanfa:addEffect(fk.EventPhaseEnd, {
  anim_type = "offensive",
  can_trigger = function(self, event, target, player, data)
    return target ~= player and player:hasSkill(yuanfa.name) and target.phase == Player.Play and
      not target.dead and player:canPindian(target)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if room:askToSkillInvoke(player, {
      skill_name = yuanfa.name,
      prompt = "#hanqing__yuanfa-invoke::"..target.id..":"..player:distanceTo(target),
    }) then
      event:setCostData(self, {tos = {target}})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = player:distanceTo(target)
    local pindian = {
      from = player,
      tos = {target},
      reason = yuanfa.name,
      fromCard = nil,
      results = {},
      extra_data = {
        hanqing__yuanfa = n,
      },
    }
    room:pindian(pindian)
    if pindian.results[target].winner == player then
      if player.dead or target.dead then return end
      local card = Fk:cloneCard("enemy_at_the_gates")
      card.skillName = yuanfa.name
      if not player:canUseTo(card, target) then return end
      local use = {
        from = player,
        tos = {target},
        card = card,
        extra_data = {
          num = n,
        }
      }
      room:useCard(use)
    elseif pindian.results[target].winner == target and not player.dead then
      room:setPlayerMark(player, yuanfa.name, 1)
      room:invalidateSkill(player, yuanfa.name)
    end
  end,
})

yuanfa:addEffect(fk.PindianCardsDisplayed, {
  can_refresh = function (self, event, target, player, data)
    return player == data.from and data.reason == yuanfa.name and
      data.extra_data and data.extra_data.hanqing__yuanfa
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:changePindianNumber(data, player, -data.extra_data.hanqing__yuanfa, yuanfa.name)
  end,
})

yuanfa:addEffect(fk.TurnStart, {
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark(yuanfa.name) > 0
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player, yuanfa.name, 0)
    player.room:validateSkill(player, yuanfa.name)
  end,
})

return yuanfa
